<?php
/* SVN FILE: $Id: market.php 219 2009-09-15 18:01:46Z supersmashbrothers $ */
/**
* ibMarket 2
* IP.Board 3.0
* ibMarket Registry
* ibMarket common functions
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 219 $
* @lastrevision $Date: 2009-09-15 18:01:46 +0000 (Tue, 15 Sep 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-09-15 18:01:46 +0000 (Tue, 15 Sep 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket2/trunk/admin/applications_addon/other/ibmarket/tasks/market.php $
*/

if ( ! defined( 'IN_IPB' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files.";
	exit();
}

class task_item
{
	/**
	 * Parent task manager class
	 *
	 * @access	protected
	 * @var		object
	 */
	protected $class;

	/**
	 * This task data
	 *
	 * @access	protected
	 * @var		array
	 */
	protected $task			= array();

	/**
	 * Prevent logging
	 *
	 * @access	protected
	 * @var		boolean
	 */
	protected $restrict_log	= false;
	
	/**#@+
	 * Registry Object Shortcuts
	 *
	 * @access	protected
	 * @var		object
	 */
	protected $registry;
	protected $DB;
	protected $settings;
	protected $request;
	protected $lang;
	protected $member;
	protected $cache;
	/**#@-*/
	
	/**
	 * Constructor
	 *
	 * @access	public
	 * @param 	object		ipsRegistry reference
	 * @param 	object		Parent task class
	 * @param	array 		This task data
	 * @return	void
	 */
	public function __construct( ipsRegistry $registry, $class, $task )
	{
		/* Make registry objects */
		$this->registry	  = $registry;
		$this->DB		  = $this->registry->DB();
		$this->settings   =& $this->registry->fetchSettings();
		$this->request    =& $this->registry->fetchRequest();
		$this->lang		  = $this->registry->getClass('class_localization');
		$this->member	  = $this->registry->member();
		$this->memberData =& $this->registry->member()->fetchMemberData();
		$this->cache	  = $this->registry->cache();
		$this->caches     =& $this->registry->cache()->fetchCaches();

		$this->class	= $class;
		$this->task		= $task;
	}
	
	/**
	 * Run this task
	 * 
	 * @access	public
	 * @return	void
	 */
	public function runTask()
	{
		$this->class->appendTaskLog( $this->task, 'New registrations recieved new money and post rewards are recieved' );
		
		// Get the time of the last log
		$last_log = $this->DB->buildAndFetch(array('select'=>'*','from'=>'task_logs','where'=>"log_title='".$this->task['task_title']."'",'order'=>'log_date DESC','limit'=>array(1,1)));
		$last_log['log_date'] = intval($last_log['log_date']);
		
		$this->registry->getClass('class_localization')->loadLanguageFile( array( 'public_global' ), 'core' );
		
		if(!class_exists('marketRegistry'))
		{
			require_once( IPSLib::getAppDir('ibmarket')."/sources/marketRegistry.php");
			marketRegistry::__setup();
		}
		
		if(!class_exists('class_forums'))
		{
			require_once( IPSLib::getAppDir( 'forums' ) . "/sources/classes/forums/class_forums.php" );
			$this->registry->setClass( 'class_forums', new class_forums( $this->registry ) );
			$this->registry->getClass( 'class_forums' )->forumsInit();
		}
		
		$members = array();
		$registered = array();
		$posted = array();
		$replies = array();
		$topics = array();
		$this->DB->build(array('select'=>'*','from'=>'members','where'=>"joined > ".$last_log['log_date']));
		$q = $this->DB->execute();
		while($member = $this->DB->fetch($q))
		{
			$members[$member['member_id']] = $this->settings['market_register'];
			$registered[$member['member_id']] = $this->settings['market_register'];
		}
		
		$this->DB->build(array(
								'select' => 'p.author_id,p.new_topic',
								'from' => array('posts' => 'p'),
								'add_join' => array(
														array(
																'select' => 't.forum_id',
																'from' => array('topics' => 't'),
																'where' => "p.topic_id = t.tid",
																'type' => 'left' 
															),
													),
								'where' => "p.post_date > ".$last_log['log_date'],
								'order' => 'post_date ASC',
						)	);
		$q = $this->DB->execute();
		while($post = $this->DB->fetch($q))
		{
			if($post['new_topic'])
			{
				if($this->registry->getClass( 'class_forums' )->forum_by_id[$post['forum_id']]['market_topic'])
				{
					$more_more_money = $this->registry->getClass( 'class_forums' )->forum_by_id[$post['forum_id']]['market_topic_amount'];
				}
				else
				{
					$more_more_money = $this->settings['market_post_topic'];
				}
			}
			else
			{
				if($this->registry->getClass( 'class_forums' )->forum_by_id[$post['forum_id']]['market_reply'])
				{
					$more_more_money = $this->registry->getClass( 'class_forums' )->forum_by_id[$post['forum_id']]['market_reply_amount'];
				}
				else
				{
					$more_more_money = $this->settings['market_post_reply'];
				}
				$replies[$post['topic_id']]++;
			}
			if(!isset($members[$post['author_id']]))
			{
				$members[$post['author_id']] = 0;
			}
			if(!isset($posted[$post['author_id']]))
			{
				$posted[$post['author_id']] = 0;
			}
			$members[$post['author_id']] = numbers::add($members[$post['author_id']],$more_more_money);
			$posted[$post['author_id']] = numbers::add($posted[$post['author_id']],$more_more_money);
			$topics[$post['topic_id']] = $post['topic_id'];
		}
		
		if($this->settings['market_topic_reply'] && count($replies))
		{
			if(count($topics))
			{
				$this->DB->build(array(
										'select' => 'COUNT(p.pid) as posts,p.topic_id',
										'from' => array('posts' => 'p'),
										'add_join' => array(
																array(
																		'select' => 't.starter_id',
																		'from' => array('topics' => 't'),
																		'where' => "p.topic_id = t.tid",
																		'type' => 'left' 
																	),
															),
										'where' => "p.post_date <= ".$last_log['log_date']." AND p.topic_id IN (".implode(', ',$topics).")",
										'group' => 'p.topic_id',
										'order' => 'post_date ASC',
								)	);
				$q = $this->DB->execute();
				while($post = $this->DB->fetch($q))
				{
					if($post['posts'] > $this->settings['market_topic_reply'] + 1)
					{
						continue;
					}
					
					if($post['posts'] + $replies[$post['topic_id']] > $this->settings['market_topic_reply'] + 1)
					{
						$members[$post['starter_id']] = numbers::add($members[$post['starter_id']],$this->settings['market_topic_amount']);
						$posted[$post['starter_id']] = numbers::add($posted[$post['starter_id']],$this->settings['market_topic_amount']);
					}
				}
			}
		}
		
		if(count($members) > 0)
		{
			$this->DB->build(array('select'=>'*','from'=>'members','where'=>"member_id IN (".implode(",",array_keys($members)).")"));
			$q = $this->DB->execute();
			while($member = $this->DB->fetch($q))
			{
				$this->DB->update('members',array(
													$this->settings['market_members_field'] => numbers::add($member[$this->settings['market_members_field']],$members[$member['member_id']])
				),"member_id=".$member['member_id']);
				if(isset($registered[$member['member_id']]))
				{
					$this->DB->insert('market_reward_logs',array(
																	'member_id' => $member['member_id'],
																	'l_time' => time(),
																	'location' => 'registered',
																	'l_amount' => $this->settings['market_register'],
									)							);
				}
				if(isset($posted[$member['member_id']]))
				{
					$this->DB->insert('market_reward_logs',array(
																	'member_id' => $member['member_id'],
																	'l_time' => time(),
																	'location' => 'posts',
																	'l_amount' => $posted[$member['id']],
									)							);
				}
			}
		}
		
		$this->class->unlockTask( $this->task );
	}

}